package com.yc.login.web;

import com.yc.login.bean.LoginProperteis;
import com.yc.login.web.bean.Result;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("user")
public class UserDo {

    @Resource
    LoginProperteis loginProperteis;

    @RequestMapping("props")
    LoginProperteis uploadProperteis(){
        return loginProperteis;
    }

    @Resource
    JdbcTemplate jdbc;

    @RequestMapping("login")
    public Result login(String name, String pwd,
                        HttpSession session){
        if(name==null || name.trim().isEmpty()){
            return new Result(0,"请输入用户名!",null);
        }
        // TODO 其它验证请自行完善

        String md5 = DigestUtils.md5DigestAsHex((name + pwd).getBytes());
        String sql = "select * from %s where %s = ?";
        sql = String.format(sql, loginProperteis.getUserTable(),
                loginProperteis.getPasswordColumn());
        try{
            final Map<String, Object> user = jdbc.queryForMap(sql, md5);
            // 去掉密码字段
            user.remove(loginProperteis.getPasswordColumn());
            session.setAttribute("loginedUser", user);
            return new Result(1,"登录成功!",user);
        } catch (DataAccessException e){
            e.printStackTrace();
            return new Result(0,"用户名或密码错误!",null);
        }
    }

    @RequestMapping("logout")
    public Object logout(
            @RequestHeader("Accept") String accept,
            HttpSession session, ModelAndView modelAndView){
        session.invalidate();
        if(accept.startsWith("application/json")){
            // ajax请求 => 返回 result 对象
            Result res = new Result(1, "退出成功!", null);
            return res;
        } else {
            // 表单请求 => 页面跳转
            modelAndView.setViewName("redirect:/");
            return modelAndView;
        }
    }

    @RequestMapping("myinfo")
    public Result myinfo(@SessionAttribute(required = false) Map<String, Object> loginedUser){
        if(loginedUser == null){
            return new Result(0, "未登录", null);
        } else {
            return new Result(1, "已登录", loginedUser);
        }
    }

    public static void main(String[] args) {
        System.out.println(DigestUtils.md5DigestAsHex("张三123".getBytes()));
        System.out.println(DigestUtils.md5DigestAsHex("李四123".getBytes()));
    }

}

